//
//  LYDrawingView.m
//  华康通
//
//  Created by  雷雨 on 2017/7/19.
//  Copyright © 2017年 com.huakang. All rights reserved.
//

#import "LYDrawingView.h"

@interface LYDrawingView()

// 声明一条贝塞尔曲线
@property(nonatomic, strong) UIBezierPath *bezier;
// 创建一个存储后退操作记录的数组
@property(nonatomic, strong) NSMutableArray *cancleArr;
@property(nonatomic, strong) NSMutableArray *pointXs;
@property(nonatomic, strong) NSMutableArray *pointYs;


@end

@implementation LYDrawingView

-(NSMutableArray*)pointXs
{
    if (!_pointXs)
    {
        _pointXs = [[NSMutableArray alloc]initWithCapacity:0];
    }
    return _pointXs;
}

-(NSMutableArray*)pointYs
{
    if (!_pointYs)
    {
        _pointYs = [[NSMutableArray alloc]initWithCapacity:0];
    }
    return _pointYs;
}

// 初始化一些参数
- (void)initDrawingView
{
    self.backgroundColor = ClEARColor;
    self.color = YYColor;
    self.lineWidth = 2;
    self.allLines = [NSMutableArray new];
    self.cancleArr = [NSMutableArray new];
    UILabel *placeHoalderLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    placeHoalderLabel.frame = CGRectMake(0, (self.frame.size.height - 100)/2, self.frame.size.width, 100);
    placeHoalderLabel.textAlignment = NSTextAlignmentCenter;
    placeHoalderLabel.text = @"签名区域";
    placeHoalderLabel.font = SetFont(35.0);
    placeHoalderLabel.alpha = 0.8;
    placeHoalderLabel.textColor = [UIColor grayColor];
    self.placeHoalderLabel = placeHoalderLabel;
    [self addSubview:placeHoalderLabel];
}

- (void)doBack
{
    self.placeHoalderLabel.hidden = NO;
    self.placeHoalderLabel.text = @"签名区域";
    [self.pointXs removeAllObjects];
    [self.pointYs removeAllObjects];
    [self.allLines removeAllObjects];
    [self setNeedsDisplay];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    self.placeHoalderLabel.hidden = YES;
    self.placeHoalderLabel.text = nil;
    // 贝塞尔曲线
    self.bezier = [UIBezierPath bezierPath];
    // 获取触摸的点
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:self];
    [self.pointXs addObject:[NSNumber numberWithFloat:point.x]];
    [self.pointYs addObject:[NSNumber numberWithFloat:point.y]];
    // 设置贝塞尔起点
    [self.bezier moveToPoint:point];
    // 在字典保存每条线的数据
    NSMutableDictionary *tempDic = [NSMutableDictionary new];
    [tempDic setObject:self.color forKey:@"color"];
    [tempDic setObject:[NSNumber numberWithFloat:self.lineWidth] forKey:@"lineWidth"];
    [tempDic setObject:self.bezier forKey:@"line"];
    // 存入线
    [self.allLines addObject:tempDic];
}

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:self];
    [self.pointXs addObject:[NSNumber numberWithFloat:point.x]];
    [self.pointYs addObject:[NSNumber numberWithFloat:point.y]];
    [self.bezier addLineToPoint:point];
    //重绘界面
    [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect
{
    for (int i = 0; i < self.allLines.count; i++)
    {
        NSDictionary *temDic = self.allLines[i];
        UIColor *color = temDic[@"color"];
        CGFloat width = [temDic[@"lineWidth"] floatValue];
        UIBezierPath *path = temDic[@"line"];
        [color setStroke];
        [path setLineWidth:width];
        [path stroke];
    }
}

- (void)saveImage:(SaveSuccessBlock)saveSuccessBlock
{
    UIImage *currentImage = [self compressOriginalImage:[self getTextImage] toSize:CGSizeMake(160, 40)];
    //图片保存到本地
//    UIImageWriteToSavedPhotosAlbum(currentImage, nil, nil, nil);
    if (self.pointXs.count > 0 && self.pointYs > 0)
    {
        if (saveSuccessBlock)
        {
            saveSuccessBlock(currentImage,YES);
        }
    }
    else
    {
        if (saveSuccessBlock)
        {
            saveSuccessBlock(currentImage,NO);
        }
    }
}
//把图片变成想要的160x40的尺寸
-(UIImage *)compressOriginalImage:(UIImage *)image toSize:(CGSize)size
{
    UIView* myView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, size.width, size.height)];
    myView.backgroundColor = ClEARColor;
    UIImageView* imageView = [[UIImageView alloc]init];
    imageView.backgroundColor = ClEARColor;
    imageView.image = image;
    UIGraphicsBeginImageContext(size);
    if (image.size.width/image.size.height > 4)
    {
        CGSize sizeOfImage = CGSizeMake(size.width, size.width * image.size.height/image.size.width);
        NSLog(@"sizeOfImage的宽:%f。sizeOfImage的高：%f",sizeOfImage.width,sizeOfImage.height);
        imageView.frame = CGRectMake(0, (size.height - sizeOfImage.height)/2, size.width, sizeOfImage.height);
    }
    else if (image.size.width/image.size.height < 4)
    {
        CGSize sizeOfImage = CGSizeMake(size.height * image.size.width/image.size.height, size.height);
        NSLog(@"sizeOfImage的宽:%f。sizeOfImage的高：%f",sizeOfImage.width,sizeOfImage.height);
        imageView.frame = CGRectMake((size.width - sizeOfImage.width)/2, 0, sizeOfImage.width, size.height);
    }
    else
    {
        imageView.frame = CGRectMake(0, 0, size.width, size.height);
        [image drawInRect:CGRectMake(0,0, size.width, size.height)];
    }
    [myView addSubview:imageView];
    // 截屏
    UIGraphicsBeginImageContext(myView.frame.size);
    [myView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    // 截取画板尺寸
    CGImageRef sourceImageRef = [newImage CGImage];
    CGImageRef newImageRef = CGImageCreateWithImageInRect(sourceImageRef, CGRectMake(0 , 0, size.width, size.height));
    UIImage *scaleImage = [UIImage imageWithCGImage:newImageRef];
    //把图片保存到本地转成png
    [imageView removeFromSuperview];
    imageView = nil;
    myView = nil;
    return scaleImage;
}

//根据签名文字区域截取文字区域得到图片
- (UIImage*)getTextImage
{
    UIImage *newImage = nil;
    if (self.pointXs.count > 0 && self.pointYs > 0)
    {
        CGFloat minXValue = [[self.pointXs valueForKeyPath:@"@min.floatValue"] floatValue];
        CGFloat maxXValue = [[self.pointXs valueForKeyPath:@"@max.floatValue"] floatValue];
        CGFloat minYValue = [[self.pointYs valueForKeyPath:@"@min.floatValue"] floatValue];
        CGFloat maxYValue = [[self.pointYs valueForKeyPath:@"@max.floatValue"] floatValue];
        // 截屏
        UIGraphicsBeginImageContext(self.bounds.size);
        [self.layer renderInContext:UIGraphicsGetCurrentContext()];
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        // 截取画板尺寸
        CGImageRef sourceImageRef = [image CGImage];
        CGImageRef newImageRef = CGImageCreateWithImageInRect(sourceImageRef, CGRectMake(minXValue - 8 , minYValue - 8, maxXValue - minXValue + 16, maxYValue - minYValue + 16));
        newImage = [UIImage imageWithCGImage:newImageRef];
    }
    else
    {
        // 截屏
        UIGraphicsBeginImageContext(self.bounds.size);
        [self.layer renderInContext:UIGraphicsGetCurrentContext()];
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        // 截取画板尺寸
        CGImageRef sourceImageRef = [image CGImage];
        CGImageRef newImageRef = CGImageCreateWithImageInRect(sourceImageRef, CGRectMake(0 , 0, self.bounds.size.width, self.bounds.size.height));
        newImage = [UIImage imageWithCGImage:newImageRef];
    }
    return newImage;
}

/**
 * 图片压缩到指定大小
 * @param targetSize 目标图片的大小
 * @param sourceImage 源图片
 * @return 目标图片
 */
//- (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize withSourceImage:(UIImage *)sourceImage
//{
//    UIImage *newImage = nil;
//    CGSize imageSize = sourceImage.size;
//    CGFloat width = imageSize.width;
//    CGFloat height = imageSize.height;
//    CGFloat targetWidth = targetSize.width;
//    CGFloat targetHeight = targetSize.height;
//    CGFloat scaleFactor = 0.0;
//    CGFloat scaledWidth = targetWidth;
//    CGFloat scaledHeight = targetHeight;
//    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
//    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
//    {
//        CGFloat widthFactor = targetWidth / width;
//        CGFloat heightFactor = targetHeight / height;
//        if (widthFactor > heightFactor)
//            scaleFactor = widthFactor; // scale to fit height
//        else
//            scaleFactor = heightFactor; // scale to fit width
//        scaledWidth= width * scaleFactor;
//        scaledHeight = height * scaleFactor;
//        // center the image
//        if (widthFactor > heightFactor)
//        {
//            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
//        }
//        else if (widthFactor < heightFactor)
//        {
//            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
//        }
//    }
//    UIGraphicsBeginImageContext(targetSize); // this will crop
//    CGRect thumbnailRect = CGRectZero;
//    thumbnailRect.origin = thumbnailPoint;
//    thumbnailRect.size.width= scaledWidth;
//    thumbnailRect.size.height = scaledHeight;
//    [sourceImage drawInRect:thumbnailRect];
//    newImage = UIGraphicsGetImageFromCurrentImageContext();
//    if(newImage == nil)
//    NSLog(@"could not scale image");
//    //pop the context to get back to the default
//    UIGraphicsEndImageContext();
//    return newImage;
//}

- (UIImage*) imageToTransparent:(UIImage*) image
{
    // 分配内存
    const int imageWidth = image.size.width;
    const int imageHeight = image.size.height;
    size_t bytesPerRow = imageWidth * 4;
    uint32_t* rgbImageBuf = (uint32_t*)malloc(bytesPerRow * imageHeight);
    // 创建context
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(rgbImageBuf, imageWidth, imageHeight, 8, bytesPerRow, colorSpace,
                                                 kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipLast);
    CGContextDrawImage(context, CGRectMake(0, 0, imageWidth, imageHeight), image.CGImage);
    // 遍历像素
    int pixelNum = imageWidth * imageHeight;
    uint32_t* pCurPtr = rgbImageBuf;
    for (int i = 0; i < pixelNum; i++, pCurPtr++)
    {
        
        //        //去除白色...将0xFFFFFF00换成其它颜色也可以替换其他颜色。
        //        if ((*pCurPtr & 0xFFFFFF00) >= 0xffffff00) {
        //
        //            uint8_t* ptr = (uint8_t*)pCurPtr;
        //            ptr[0] = 0;
        //        }
        //接近白色
        //将像素点转成子节数组来表示---第一个表示透明度即ARGB这种表示方式。ptr[0]:透明度,ptr[1]:R,ptr[2]:G,ptr[3]:B
        //分别取出RGB值后。进行判断需不需要设成透明。
        uint8_t* ptr = (uint8_t*)pCurPtr;
        if (ptr[1] > 240 && ptr[2] > 240 && ptr[3] > 240)
        {
            //当RGB都大于240则比较接近白色的都将透明度设为0.-----即接近白色的都设置为透明。某些白色背景具有杂质就会去不干净，用这个方法可以去干净
            ptr[0] = 0;
        }
    }
    // 将内存转成image
    CGDataProviderRef dataProvider =CGDataProviderCreateWithData(NULL, rgbImageBuf, bytesPerRow * imageHeight, nil);
    CGImageRef imageRef = CGImageCreate(imageWidth, imageHeight,8, 32, bytesPerRow, colorSpace,
                                        kCGImageAlphaLast |kCGBitmapByteOrder32Little, dataProvider,
                                        NULL, true,kCGRenderingIntentDefault);
    CGDataProviderRelease(dataProvider);
    UIImage* resultUIImage = [UIImage imageWithCGImage:imageRef];
    // 释放
    CGImageRelease(imageRef);
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);
    return resultUIImage;
}

@end
